<?php
$adm_menu = "1";

include("config.php");
if (!isset($_SESSION["auser"]) || $_SESSION["auser"] == "" || $_SESSION['agroup'] != "WEB_ADMIN") header('Location: index.php');

if (isset($_REQUEST["code"])){
	$_SESSION["sel_user"] = $_REQUEST["code"];
}
if (isset($_REQUEST["ret"])){
	$_SESSION["page_ret"] = $_REQUEST["ret"];
} else {
	if (!isset($_SESSION["page_ret"])) {
		$_SESSION["page_ret"] = "users";
	}
}

$db_www = new DB($server_username,$server_pass,$server_db,$server,$driver);
$db_rdata = new DB($rdata_server_username,$rdata_server_pass,$rdata_server_db,$rdata_server,$rdata_driver);

$err = "";
if (isset($_REQUEST["clearmsg"])){
	$sql = "exec web_clear_last_msg @N60_KODAS_SM= '".addslashes_mssql($_REQUEST["code"])."'";
	$db_www->execute($sql);
}
if (isset($_REQUEST["findim"])){
		$test_q = "SELECT N08_kodas_ks,N08_PAV FROM n08_klij WHERE N08_kodas_ks = '".$_REQUEST["imcode"]."'";
		//echo $test_q; 
		$im = $db_www->returnInfo($test_q);	
		if ($im == null) {
			$impav = "";
			$uid = "";
			$err .= "<br>Nerasta įmonė su tokiu kodu!";
		} else {
			$impav = $im["N08_PAV"];
			$uid = $_REQUEST["imcode"];
		}
}


if (isset($_REQUEST["act"]) && !isset($_REQUEST["clearmsg"]) && !isset($_REQUEST["findim"])){
	if ($_REQUEST["act"] == "change" && isset($_REQUEST["descr"]) && isset($_REQUEST["nr"])) {
		$sql = "exec web_change_card_descr "
		. "@type='ADMIN',"
		. "@pastabos='".iconv('UTF-8','windows-1257',addslashes_mssql($_REQUEST["descr"]))."',"
		. "@imkodas='',"
		. "@kortele='".iconv('UTF-8','windows-1257', addslashes_mssql($_REQUEST["nr"]))."'";		
		$db_www->execute($sql);	
		
		logAction("Tiekėjas koreguoja:" . $_REQUEST["nr"],3);
	} else if ($_REQUEST["act"] == "block") {
		//$ustatus_query = str_replace("<kodas>", addslashes_mssql($_REQUEST["code"]), $ustatus_query);
		//$ustatus_query = str_replace("<status>", "1", $ustatus_query);
		//$db_www->execute($ustatus_query);		
	} else if ($_REQUEST["act"] == "unblock" ) {
		//$ustatus_query = str_replace("<kodas>", addslashes_mssql($_REQUEST["code"]), $ustatus_query);
		//$ustatus_query = str_replace("<status>", "0", $ustatus_query);
		//$db_www->execute($ustatus_query);		
	} else if ($_REQUEST["act"] == "unblockc" && isset($_REQUEST["nr"])) {
		$sql = "exec web_change_card_status "
		. "@type='TIEK_BLOK',"
		. "@action='UNBLOCK',"
		. "@imkodas='',"
		. "@kortele='".iconv('UTF-8','windows-1257', addslashes_mssql($_REQUEST["nr"]))."'";		
		$db_www->execute($sql);	
		
		logAction("Tiekėjas atblokuoja:" . $_REQUEST["nr"],2);
	} else if ($_REQUEST["act"] == "blockc" && isset($_REQUEST["nr"])) {
		$sql = "exec web_change_card_status "
		. "@type='TIEK_BLOK',"
		. "@action='BLOCK',"
		. "@imkodas='',"
		. "@kortele='".iconv('UTF-8','windows-1257', addslashes_mssql($_REQUEST["nr"]))."'";		
		$db_www->execute($sql);	

		logAction("Tiekėjas užblokuoja:" . $_REQUEST["nr"],2);	
	} else if ($_REQUEST["act"] == "save") {		
		//ar yra toks imones kodas
		$test_q = "SELECT N08_kodas_ks,N08_PAV FROM n08_klij WHERE N08_kodas_ks = '".$_REQUEST["imcode"]."'";
		$im = $db_www->returnInfo($test_q);		
		if (empty($im)) {
			$err .= "<br>Nerasta įmonė su tokiu kodu!";
		}
		//ar ivestas slaptazodis
		if (trim($_REQUEST["pass"])==""){
			$err .= "<br>Neįvestas slaptažodis!";
		}
		//ar ivestas vartotojo id
		if (trim($_REQUEST["uid"])==""){
			$err .= "<br>Neįvestas vartotojo id!";
		}
		//ar teisingas el pastas
		if(!filter_var($_REQUEST["email"], FILTER_VALIDATE_EMAIL))
		{
			$err .= "<br>Neteisingas el. pašto adresas!";
		}
		if ($_REQUEST["code"] == "0") { //naujas
		
			//ar dar nera vartotojo su tokiu vartotojo id
			
			$test_q = "SELECT * FROM n60_asm WHERE n60_kodas_sm = '".$_REQUEST["uid"]."' AND n60_kodas_gs='WEB'";
			$usr = $db_www->returnInfo($test_q);		
			if (!empty($usr)) {
				$err .= "<br>Vartotojas su tokiu id jau egzistuoja!";
			}			
			//jei nebuvo klaidu
			if ($err == ""){

				
			}
			
		} else { //redagavimas
			//jei nebuvo klaidu
			if ($err == ""){		
				$sql = "exec web_update_user "
				. "@n60_kodas_ks='".addslashes_mssql($im["N08_kodas_ks"])."',"
				. "@n60_pav2='".addslashes_mssql($im["N08_PAV"])."',"
				. "@n60_pareigos='".iconv('UTF-8','windows-1257', addslashes_mssql($_REQUEST["pass"]))."',"
				. "@n60_vardas='".iconv('UTF-8','windows-1257', addslashes_mssql($_REQUEST["firstname"]))."',"
				. "@n60_pav='".iconv('UTF-8','windows-1257', addslashes_mssql($_REQUEST["lastname"]))."',"
				. "@n60_e_mail='".addslashes_mssql($_REQUEST["email"])."',"
				. "@N60_KODAS_SM='".addslashes_mssql($_REQUEST["code"])."',"
				. "@N08_kodas_ls_5='".addslashes_mssql($_REQUEST["sekimas"])."',"
				. "@N08_suma_wk_limit='".addslashes_mssql($_REQUEST["crlimit"])."'";
				
				$db_www->execute($sql);
				
				
				$sql = "exec web_ins_upd_klij "
				. "@N08_c_kodas_ks='".addslashes_mssql($im["N08_kodas_ks"])."',"
				. "@N08_c_suma_wk_per='".addslashes_mssql($_REQUEST["crpercent"])."',"
				. "@n08_c_kreditas_dienos='".addslashes_mssql($_REQUEST["crlate"])."',"
				. "@N08_kodas_ls_5='".addslashes_mssql($_REQUEST["sekimas"])."',"
				. "@n08_c_invoice='".addslashes_mssql(trim($_REQUEST["tinvoice"]))."'";
				$db_rdata->execute($sql);
				
				header('Location: users.php');
			}			
		}
	}
}	
include("header.php");
include("menu.php");


?>


<SCRIPT language="JavaScript">
<!--

function isUnsignedInteger(s) {
  return (s.toString().search(/^[0-9]+$/) == 0);
}



function getRandomNum(lbound, ubound) {
return (Math.floor(Math.random() * (ubound - lbound)) + lbound);
}

function getRandomChar(number, lower, upper, other, extra) {
var numberChars = "0123456789";
var lowerChars = "abcdefghijklmnopqrstuvwxyz";
var upperChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var otherChars = "`~!@#$%^&*()-_=+[{]}\\|;:'\",<.>/? ";
var charSet = extra;
if (number == true)
charSet += numberChars;
if (lower == true)
charSet += lowerChars;
if (upper == true)
charSet += upperChars;
if (other == true)
charSet += otherChars;
return charSet.charAt(getRandomNum(0, charSet.length));
}

function getPassword(length, extraChars, firstNumber, firstLower, firstUpper, firstOther,
latterNumber, latterLower, latterUpper, latterOther) {
var rc = "";
if (length > 0)
rc = rc + getRandomChar(firstNumber, firstLower, firstUpper, firstOther, extraChars);
for (var idx = 1; idx < length; ++idx) {
rc = rc + getRandomChar(latterNumber, latterLower, latterUpper, latterOther, extraChars);
}
return rc;
}

function generate(){	
	document.forma.pass.value = getPassword(8,true,true,true,true,false,true,true,true,false);
}


//-->
</SCRIPT>

<?php



	if (isset($_REQUEST["code"]) && $_REQUEST["code"] != "0") {
		$code = $_REQUEST["code"];
		$uid = $code;		
		if (isset($_REQUEST["uid"])) {
			$sql = str_replace("<kodas>", addslashes_mssql($_REQUEST["uid"]), $uinfo_query);
		} else {
			$sql = str_replace("<kodas>", addslashes_mssql($uid), $uinfo_query);
		}
		//echo $uinfo_query;
		$u = $db_www->returnInfo($sql);
		if ($u == null) die("nerastas vartotojas");
		else {
			$i_query = str_replace("<kodas>", $u["n60_kodas_sm"], $i_query);
			$imone = $db_www->returnInfo($i_query);
			
			$skola_query = str_replace("<im_kodas>", $u["n60_kodas_sm"], $skola_query);
			$sinfo = $db_www->returnInfo($skola_query);	
			if (!empty($sinfo)) {
				$dskola=$sinfo["skola"];
			} else {
				$dskola=0;
			}			
			
			$q = "SELECT * FROM n08_klij_c WHERE N08_c_kodas_ks='".addslashes_mssql($_REQUEST["code"])."'";
			$rimone = $db_rdata->returnInfo($q);
			
			
		}
		if (!isset($impav)){
			$impav = $u["n60_pav2"];		
		}
		$msg = $u["n60_poz_date"];

		if (!isset($_REQUEST["imcode"])) {
			$imcode = trim($u["n60_kodas_ks"]);			
		} else {
			$imcode = $_REQUEST["imcode"];			
		}
		if (!isset($_REQUEST["pass"])) {
			$pass = iconv('windows-1257','UTF-8', trim($u["n60_pareigos"]));			
		} else {
			$pass = $_REQUEST["pass"];			
		}	
		if (!isset($_REQUEST["firstname"])) {
			$firstname = iconv('windows-1257','UTF-8',trim($u["n60_vardas"]));			
		} else {
			$firstname = $_REQUEST["firstname"];			
		}	
		if (!isset($_REQUEST["lastname"])) {
			$lastname = iconv('windows-1257','UTF-8',trim($u["n60_pav"]));			
		} else {
			$lastname = $_REQUEST["lastname"];			
		}
		if (!isset($_REQUEST["email"])) {
			$email =trim($u["n60_e_mail"]);			
		} else {
			$email = $_REQUEST["email"];			
		}	
	} else {
		$code = "0";
		if (!isset($_REQUEST["imcode"])) {
			$imcode = "";		
		} else {
			$imcode = $_REQUEST["imcode"];			
		}
		if (!isset($uid)) {
			if (!isset($_REQUEST["uid"])) {
				$uid = "";		
			} else {
				$uid = $_REQUEST["uid"];			
			}		
		}
		if (!isset($_REQUEST["pass"])) {
			$pass = "";			
		} else {
			$pass = $_REQUEST["pass"];			
		}	
		if (!isset($_REQUEST["firstname"])) {
			$firstname = "";			
		} else {
			$firstname = $_REQUEST["firstname"];			
		}	
		if (!isset($_REQUEST["lastname"])) {
			$lastname = "";		
		} else {
			$lastname = $_REQUEST["lastname"];			
		}
		if (!isset($_REQUEST["email"])) {
			$email = "";		
		} else {
			$email = $_REQUEST["email"];			
		}			
	}
	




	
		
		$tit = "Kliento duomenys";		
		$disp = "";		
		$disp2 = "";


?>
<form method="post" name='forma' action='user.php?act=save'>
<input id="code" type="hidden" name="code" value="<?php echo $code?>">
<table class="innercont" cellspacing="0" cellpadding="10" border="0">
<tr><td class="leftcol2">


<?php
printUserEditMenu($_SESSION["page_ret"],$_REQUEST["code"],$u["n60_kodas_sm"],$u["n60_pareigos"]);
?>


</td><td class="centercol">
<?php
if ($err != ""){
	echo "<p style='background-color:transparent;color:red;font-weight:bold;font-size:10px;'>".$err."</p>";
}
?>
<div class="title2"><?php echo $tit?></div>
<table width="100%" border="0">
<tr><td valign="top" class="fieldtitle">Įmonės kodas:</td><td valign="top" colspan="2" class="fieldtitle">Įmonės pavadinimas:</td></tr>
<tr><td valign="top">
<input id='imcode' class="inp" type='text' name="imcode" value="<?php echo htmlspecialchars($imcode) ?>"><br>
<div style="float:right;"><A class='flink' href="#" onclick='document.forma.action="user.php?act=save&findim=1";document.forma.submit()'>Ieškoti</A></div>
</td><td valign="top" colspan="2">
<input style="width:275px;" id='impav' class="inp" type='text' name="pav" value="<?php echo htmlspecialchars(@iconv('windows-1257', 'UTF-8',$impav), ENT_QUOTES)?>" readonly="readonly">
</td></tr>

<tr><td valign="top" class="fieldtitle">Vartotojo ID:</td><td valign="top" class="fieldtitle">Slaptažodis:</td><td valign="top" class="fieldtitle">El. paštas:</td></tr>
<tr><td valign="top"><input id='uid' class="inp" type='text' name="uid" value="<?php echo htmlspecialchars($uid)?>"<?php	if ($code != "0") 
		echo ' readonly="readonly"'; ?>"></td>
	<td valign="top"><input id="pass" class="inp" type='text' name="pass" value="<?php echo htmlspecialchars($pass, ENT_QUOTES) ?>"><br>
	<div style="float:right;"><A class='flink' href="javascript:generate()">Generuoti</A></div></td><td valign="top">
	<input id='email' class="inp" type='text' name="email" value="<?php echo htmlspecialchars($email);?>"></td></tr>
<tr><td valign="top" class="fieldtitle">Vardas:</td><td valign="top" class="fieldtitle">Pavardė:</td><td valign="top" class="fieldtitle">Pask. pranešimas:</td></tr>
<tr><td valign="top" ><input id='firstname' class="inp" type='text' name="firstname" value="<?php echo htmlspecialchars($firstname);?>"></td>
<td valign="top"><input id='lastname' class="inp" type='text' name="lastname" value="<?php echo htmlspecialchars($lastname);?>"></td><td valign="middle"><input class="inp" type="text" value="<?php echo iconv('windows-1257', 'UTF-8',$msg);?>"><br>
<div style="float:right;">
<a class="flink" href="#" onclick='document.forma.action="user.php?code=<?php echo $_REQUEST["code"];?>&clearmsg=1";document.forma.submit()'>Išvalyti</a>
</div>
</td></tr>
<tr><td colspan="2" valign="top" class="fieldtitle" colspan="2">Sąskaitos šablonas:</td><td valign="top" class="fieldtitle"></td></tr>
<tr><td colspan="2" valign="top" colspan="2">

<div style="position: relative;">
<select name="tinvoice" class="select2" id='tinvoice'>
<option value=" ">saskaita.pdf</option>
<?php

$selt = "";
if (isset($rimone) && trim($rimone["n08_c_invoice"]) != "") {
	$selt = trim($rimone["n08_c_invoice"]);
}


$files = scandir("template/invoice/");
   
foreach ($files as $file) {
	if (endsWith($file,'.docx') || endsWith($file,'.doc')) {
		echo '<option value="'.$file.'" ';
		if ($file == $selt) {
			echo "SELECTED";
		}
		echo '>'.htmlspecialchars($file).'</option>';
	}
}
?>

</select>
</div>
</td><td valign="top" class="fieldtitle"></td></tr>




<tr><td colspan="3">&nbsp;</td></tr>
<tr><td colspan="3">&nbsp;</td></tr>

</table>

</td><td class="rightcol">
<?php
if (isset($kreditas) && $kreditas == "1") {
?>
<div style="float:right;">
<div class="box">
<b>Kredito sekimo požymis</b>
<script type="text/javascript">
	function showFields(){
		poz = document.forma.sekimas.value.trim();
		
		crtable = document.getElementById("crtable");
		crlate = document.getElementById("crlate");
		if (poz == 'K00') {			
			crtable.style.display = "none";
		} else if (poz == "K01") {
			crtable.style.display = "inline";
			crlate.style.display = "none";
		} else if (poz == "K02") {
			crtable.style.display = "inline";
			crlate.style.display = "inline";
		}
	}
	
	$(document).ready(function(){	

		if (!$.browser.opera) {
    
			// select element styling
			$('select.select2').each(function(){
				var title = $(this).attr('title');
				if( $('option:selected', this).val() != ''  ) title = $('option:selected',this).text();
				$(this)
					.css({'z-index':10,'opacity':0,'-khtml-appearance':'none'})
					.after('<span class="select2">' + title + '</span>')
					.change(function(){
						val = $('option:selected',this).text();
						$(this).next().text(val);
						})
			});

		};
		
	});
</script><div>
<select name="sekimas" class="select2" onchange="showFields();">
<?php 
$tracks = $db_www->returnList($track_query);
foreach ($tracks as $track) {
	echo "<option value='".strtoupper($track["N35_KODAS_LS"])."' ";
	if (trim($track["N35_KODAS_LS"]) == trim($imone["N08_kodas_ls_5"])) {
		echo "SELECTED";
	}
	echo ">".iconv('windows-1257','UTF-8',$track["N35_PAV"])."</option>";
}	

?>
</select>
</div>
</div>
</div>
<?php
}
?>

<div style="float:right;margin-top:15px;<?php

if (trim($imone["N08_kodas_ls_5"]) == "K00"){
	echo 'display:none;';
}
?>" id="crtable" >
<table class="payments" cellspacing="0" cellpadding="5" align="right">
<tr>
<td class="paymentsth borderbottom">Kredito limitas:</td><td class="borderbottom borderlr">&nbsp;</td><td class="borderbottom center"><input style="width:60px;" id='crlimit' class="inp" type='text' name="crlimit" value="<?php echo sprintf("%01.2f",$imone["n08_suma_wk_limit"]);?>"></td>
</tr>
<?php
if ($dskola>= 0) {
if ($dskola == 0)
	$tskola = "";
else
	$tskola = $dskola;
?>
<tr>
<td class="paymentsth borderbottom">Skola:</td><td class="borderbottom borderlr" style="color:red;"><?php echo $tskola;?><td class="borderbottom center" >&nbsp;</td></td>
</tr>
<?php
} else {
?>
<tr>
<td class="paymentsth borderbottom">Likutis:</td><td class="borderbottom borderlr" >&nbsp;</td><td class="borderbottom center"><?php echo abs($dskola);?></td>
</tr>
<?php
}
if ($kreditas == "1") {

		$lastaccdate_query = str_replace("<kodas>", $imone["N08_kodas_ks"], $lastaccdate_query);
		$lastacc = $db_www->returnInfo($lastaccdate_query);

		if (!isset($lastacc["I31_OP_DATA"])) {
			$pask = "2000.01.01";
		} else {
			$pask = $lastacc["I31_OP_DATA"];
		}
		
		$k_query = str_replace("<kodas>", $imone["N08_kodas_ks"], $k_query);
		$kinfo = $db_www->returnList($k_query);
		$numbers = "'333'";
		foreach ($kinfo as $card) {
			$numbers .= ",'" . trim($card["N51_PAV"]) . "'";
		}

		$db_rdata = new DB($rdata_server_username,$rdata_server_pass,$rdata_server_db,$rdata_server,$rdata_driver);
		if (!$db_rdata->isConnected()) {	
			die("Klientų aptarnavimo sistema laikinai neveikia(rdata).");
		}
		
		$today = date("Y-m-d");
		
		$imusedcredit_query = str_replace("<kodas>", $numbers, $imusedcredit_query);		
		$imusedcredit_query = str_replace("<from>", str_replace(".","-",$pask), $imusedcredit_query);
		$imusedcredit_query = str_replace("<to>", $today, $imusedcredit_query);
		$info = $db_rdata->returnInfo($imusedcredit_query);	
		//echo $imusedcredit_query;
	    
?>
<tr>
<td class="paymentsth borderbottom">Einamojo mėnesio pirkimai:</td><td class="borderbottom borderlr" style="color:red;"><?php if($info["Kvitosuma"] == null) echo "0.00"; else echo sprintf("%01.2f",$info["Kvitosuma"]);?><td class="borderbottom center">&nbsp;</td></td>
</tr>
<tr>
<?php 
if($info["Kvitosuma"] == null){
	$nep_cred = $imone["n08_suma_wk_limit"]-$dskola;
} else {
	$nep_cred = $imone["n08_suma_wk_limit"]-$dskola -$info["Kvitosuma"];
}
?>
<td class="paymentsth borderbottom"><?php if ($nep_cred >= 0) {echo "Nepanaudotas"; } else { echo "Viršytas";}?> kreditas:</td><td class="borderbottom borderlr" >&nbsp;</td><td class="borderbottom center"><?php echo sprintf("%01.2f",$nep_cred);?></td>
</tr>
<?php
} else {
?>
<tr>
<td class="paymentsth borderbottom">Nepanaudotas kreditas:</td><td class="borderbottom borderlr" >&nbsp;</td><td class="borderbottom center"><?php echo sprintf("%01.2f",$imone["n08_suma_wk_limit"]-$dskola);?></td>
</tr>
<?php
}



?>
<tr style="background-color:white;"><td colspan="3">
<table align="right" border="0" width="300">
<tr><td style="width:50%;vertical-align:bottom;"><div id='crpercent'>Suma nuo kurios perspėti apie kredito limito išnaudojimą<br>
<input style="width:70px;"  class="inp" type='text' name="crpercent" value="<?php 
if (isset($rimone["N08_c_suma_wk_per"])) {
	echo htmlspecialchars($rimone["N08_c_suma_wk_per"]);
}
?>">
</div></td>
<td style="vertical-align:bottom;"><div id='crlate' <?php
if (trim($imone["N08_kodas_ls_5"]) !="K02"){
	echo 'style="display:none;"';
}
?>
>Sąskaitų apmokėjimo galimas vėlavimas<br>
<input style="width:35px;" class="inp" type='text' name="crlate" value="<?php 
if (isset($rimone["n08_c_kreditas_dienos"])) {
	echo htmlspecialchars($rimone["n08_c_kreditas_dienos"]);
}
?>">
</div></td></tr>
</table>
</td></tr>
</table>
</div>



</td></tr>
<tr><td>&nbsp;</td><td>

<Button id='unblockButton' class='but bgwhite nopad' onclick="window.location='<?php if ($_SESSION["page_ret"] == "users") echo "users.php"; else echo "acards.php?submit=Rodyti";?>';return false;">Atgal</Button>

</td>
<td style="text-align:right;">
<input class='but bgwhite nopad' type = "submit" value = "Išsaugoti">
</td>
</tr>
</table>
</form>
<?php
include("footer.php");
?>